// pages/pk/match/match.js
const db = wx.cloud.database();
const app=getApp();
//const $ = db.command.aggregate;//聚合操作
var docid="000"
var AA=1//题库随机数
var BB//题库随机最大范围
var arr=[]//对战的题号集
var collections=[]//题目集
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topTitle:'匹配中...',
    newPlayerName:'',
    addPlayerName:'',
    newPlayerAvatarUrl:'',
    addPlayerAvatarUrl:'',
    newPlayerIntegral:'',
    addPlayerIntegral:'',
    onHidePKImage:false,
    onHideNewPlayer:true,
    onHideAddPlayer:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({//重置data值，当玩家2匹配到废弃房间时使用
      topTitle:'匹配中...',
      newPlayerName:'',
      addPlayerName:'',
      newPlayerAvatarUrl:'',
      addPlayerAvatarUrl:'',
      newPlayerIntegral:'',
      addPlayerIntegral:'',
      onHideNewPlayer:true,
      onHideAddPlayer:true,
      onHidePKImage:true,
    })
    db.collection('pkroom')
    .aggregate()
    .match({
    people: 1
    })
    .sort({
    createTimestamp: -1
    })
    .limit(1)
    .end().then(res =>{
        console.log('聚合查询结果room',res.list);
        this.initRoom(res.list);
    })
  },
  //进入房间的初始化判断函数
  initRoom:function(room){
    if (!room.length) {
      console.log('未查询到队列,创建新房间');
      this.createEmptyRoom();
    }else{
      console.log('进入队列成功');
      this.nowPlayer = 'addPlayer';
      this.docid = room[0]._id;
      this.roomid = room[0].roomid;
      console.log(room[0]._openid);
      //查询房主的头像等信息
      db.collection('ddata').doc(room[0]._openid).get().then(res => {
        console.log(res.data)
        this.setData({
          newPlayerName:res.data.userInfo.nickName,
          newPlayerAvatarUrl:res.data.userInfo.avatarUrl,
          newPlayerIntegral:res.data.totalScore,
        })
      })
      //查询自己的头像等信息
      db.collection('ddata').doc(app.globalData.openid).get().then(res => {
        this.setData({
          addPlayerName:res.data.userInfo.nickName,
          addPlayerAvatarUrl:res.data.userInfo.avatarUrl,
          addPlayerIntegral:res.data.totalScore,
        })
      })
      this.addplayer();
      console.log('加入房间'+this.roomid);   
    };
  },
  //创建新房间函数
  createEmptyRoom:function(){
    console.log('创建新房')
    const roomid = Date.now().toString();
    BB=800//随机数的上线（题目数限制）
    arr=[]//重置arr题号内容
    collections=[]//重置collections题目内容
    var x,y//随机抽题用的临时随机数和载具
    for(let i=0;i<10;i++){
      collections[i]=new Promise((resolve,reject)=>{//用Promise方法解决并发问题
        x = Math.floor(Math.random() * (BB - AA + 1) + AA)//获取随机数
        if(arr.indexOf(x)===-1){//判断是否重复
          arr.push(x)
          //查询题目信息
          db.collection('dangshi2021').where({
            list:x
          }).get().then(res => {
            y=res.data[0]
            var item={'newList':i+1,'oldList':y.list,'title':y.title,'type':y.type,'Aselect':y.Aselect,'Bselect':y.Bselect,'Cselect':y.Cselect,'Dselect':y.Dselect,'rightA':y.rightA,'newPlayerA':[],'addPlayerA':[],'newScore':0,'addScore':0,'newTime':'','addTime':0}//获取并新增需要的单题题目信息，其中newPlayerA为数组记录选择选项和正误以及对错号图标的位置
            resolve(item)
          })
        }else{
          i=i-1
        }
      })
    }
    //等待for循环的所有内容全部返回后执行Promise获取所有题目
    var questions=[]//装载所有问题
    Promise.all(collections).then((res)=>{
      questions=res
      console.log(questions)
      let room = {
        _id:roomid,
        roomid:roomid,
        createTimestamp:roomid,
        people: 1,
        finished:-1,//-1位创建房间，0为匹配成功，1为结束了整场PK的
        start:0,//先设为0等监听到玩家2进入后再修改为1让玩家2接收到你还在游戏界面的信号
        newPlayerAnswered:false,
        addPlayerAnswered:false,
        newTotalScore:0,
        addTotalScore:0,
        Q1:questions[0],
        Q2:questions[1],
        Q3:questions[2],
        Q4:questions[3],
        Q5:questions[4],
        Q6:questions[5],
        Q7:questions[6],
        Q8:questions[7],
        Q9:questions[8],
        Q10:questions[9]
    };
    db.collection('pkroom').add({ data: room })
    .then(res =>{
        this.nowPlayer = 'newPlayer';
        this.docid = res._id;
        this.roomid = roomid;
        console.log('创建房间'+this.roomid); 
        this.waitJionGame();
    })
    }).catch((err)=>{
      console.log(err);
    })
  },
  //随机匹配监听玩家加入函数
  waitJionGame:function(){
    //获取房主自己的头像等信息
    db.collection('ddata').doc(app.globalData.openid).get().then(res => {
      this.setData({
        newPlayerName:res.data.userInfo.nickName,
        newPlayerAvatarUrl:res.data.userInfo.avatarUrl,
        newPlayerIntegral:res.data.totalScore,
        onHideNewPlayer:false
      })
    })
    console.log('正在匹配对手')
    //监听玩家2进入
    let docid = this.docid;
    this.player = db.collection('pkroom')
    .where({
      _id: docid
    })
    .watch({
      onChange: snapshot => {
        const docChange = snapshot.docChanges[0];
        const doc = snapshot.docs[0];
        console.log('监听玩家进入', snapshot);
        if (docChange.dataType === 'update' && doc.people === 2) {
          console.log('匹配成功');
          //监听到玩家进入后查询并显示玩家信息
          db.collection('ddata').doc(doc._openidAdd).get().then(res => {//暂用李小磊的实际应该是doc._openidAdd
            this.setData({
              addPlayerName:res.data.userInfo.nickName,
              addPlayerAvatarUrl:res.data.userInfo.avatarUrl,
              addPlayerIntegral:res.data.totalScore,
              onHideAddPlayer:false,
              onHidePKImage:false,
              topTitle:'匹配结果：'
            })
          })
          //修改一下数据库的数据让玩家2知道，防止废弃数据影响体验
          db.collection('pkroom').doc(this.roomid).update({
            data: {
              start: 1
            },
            success: function(res) {
              console.log('房主依然在游戏内')
            }
          })
          this.player.close();
          let that=this
          setTimeout(function(){
            wx.redirectTo({
              url: '../matching/matching?player=newPlayer&_id='+that.roomid+'&_openid='+app.globalData.openid+"&_openidAdd="+doc._openidAdd,
            })
          },3000)

        }
      },
      onError: error => {
          console.log(error);
      }
    })
  },
  //后续加入玩家修改数据库操作函数
  addplayer() {
    let that=this
    let docid = this.docid;
    let _openidAdd=app.globalData.openid
    let redirect=false//判断页面是否发生了挑战
    console.log('玩家2的openid为'+_openidAdd);
     wx.cloud.callFunction({
       name: 'updateDoc',
       data: {
         collection: 'pkroom',
         docid: docid,
         people: 2,
         _openidAdd:_openidAdd,
         finished:0//不传也可以，直接在云函数里写0
       }
     }).then(res => {
         console.log('更新人数成功',res);
         //显示两个人的头像等信息
         this.setData({
           onHideAddPlayer:false,
           onHideNewPlayer:false,
           onHidePKImage:false,
           topTitle:'匹配结果'
         })
         //监听房主是否还在房间内
         that.player2 = db.collection('pkroom')
         .where({
           _id: this.roomid
         })
         .watch({
           onChange: snapshot => {
             console.log('有情况')
            //  const docChange = snapshot.docChanges[0];
             const doc = snapshot.docs[0];
             console.log('监听房主更新', snapshot);
             if (doc.start === 1) {
               console.log('准备进入PK界面');
               that.player2.close();
               setTimeout(function(){
                wx.redirectTo({
                  url: '../matching/matching?player=addPlayer&_id='+that.roomid+'&_openid='+doc._openid+'&_openidAdd='+app.globalData.openid,
                })
               },3000)
               redirect=true//提醒后续页面已经跳转
             }
           },
           onError: error => {
               console.log(error);
           }
         })
         //5秒内房主没有响应则重新匹配
         setTimeout(function(){
           console.log('未接收到反馈，重新加载页面')
           if(redirect){
             return
           }else{
            that.player2.close()
            that.onLoad()
           }
         },5000)
     }).catch(err => {
         console.log(err);
     })
 },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //退出页面就关闭监听
    this.player.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})